from django.core.cache import cache


class CacheHandle:
    def __init__(self, cache_name: str):
        self.cache_name = cache_name

    def update_dict(self, update: dict = None):
        """
        将一个字典添加到cache的字典中，若新字典中键在cache中的字典里也有，覆盖它
        """
        # 如果传入参数的类型不是字典
        if type(update) is not dict:
            raise CacheException

        temp = cache.get(self.cache_name)
        temp.update(update)
        cache.set(self.cache_name, temp, None)
        return True

    def search_dict(self, search: any = None):
        """
        若指定的缓存不存在，或者指定的缓存中没有想要的键值对，返回None
        :param search:
        :return:
        """
        try:
            return cache.get(self.cache_name)[search]
        except TypeError or KeyError:
            return None

    # 删除键值对
    def delete_dict(self, delete: any = None):
        temp = cache.get(self.cache_name)
        temp.pop(delete)
        cache.set(self.cache_name, temp, None)
        return True

    # 添加cache
    def set_cache(self, add: any = None, time: int = None):
        """
        新添加的键若存在，老的键将被覆盖
        :param add:
        :param time:
        :return:
        """
        cache.set(self.cache_name, add, time)
        return True

    # 添加cache
    def add_cache(self, add: any = None, time: int = None) -> bool:
        """
        新添加的键若存在,直接返回false，否则添加并返回true
        :param add:
        :param time:
        :return:
        """
        return cache.add(self.cache_name, add, time)

    # 删除cache自身
    def delete_cache(self):
        """
        如果要删除的缓存本身就不存在，也会返回True
        :return:
        """
        cache.delete(self.cache_name)
        return True

    # 返回cache
    def show_cache(self):
        """
        如果不存在则返回None
        :return:
        """
        return cache.get(self.cache_name)

    # 验证某缓存是否存在
    def exist_cache(self):
        if cache.get(self.cache_name) is None:
            return False
        else:
            return True


# cache操作的异常类
class CacheException(Exception):
    """业务异常类"""
    pass
